//
// Created by Soar Qin on 2017/8/22.
// Copyright (c) 2017 Soar Qin. All rights reserved.
//

#pragma once

#include "io_base.hh"

namespace core::async {

struct TCPEndpointContext;
class IPAddr;

class TCPEndpoint: public IoBase {
    DISABLE_CLASS_COPY(TCPEndpoint);
public:
    enum :uint32_t {
        READ = 1,
        WRITE = 2,
    };

    explicit TCPEndpoint(Loop &loop);
    ~TCPEndpoint() override;
    bool bind(int fd);
    bool connect(const IPAddr &addr);
    bool connect(const std::string &address);
    bool connect(const std::string &ip, uint16_t port);

    size_t read(void *buf, size_t size);
    int write(const void *buf, size_t size);
    int writeTo(TCPEndpoint *to);
    void shutdown();
    inline void setDeleteOnClose(bool on = true) { deleteOnClose_ = on; }
    inline bool isDeleteOnClose() { return deleteOnClose_; }

    virtual void onRead() = 0;
    virtual void onWrite() {}
    virtual void onConnected() {}
    virtual void onClosed();

    void enable(uint32_t op);

protected:
    TCPEndpointContext *context_;
    bool deleteOnClose_ = false;
};

}
